/**
 * @class   wosh::BusMT
 * @brief   Bus implementation with process resilience and parallel computation
 *         (multi-thread architecture).
 *
 *         Messages are posted asynchronously. 
 *         The order of messages' arrival is not predictable, Listeners may
 *         receive more messages at same time.
 *
 *         Processes are organized as a hierarchical group (coordinator + N workers)
 *         Each worker process dispatches a Message to the listeners (similar
 *         to wosh::BusRing iteration) and it is independent.
 *
 *         This implementation is N-1 fault tolerant.
 *
 *         Coordinator's process (implemented within this class) selects
 *         the first available worker-process (wosh::BusMTWorker) for each
 *         message in the queue. 
 *
 ****************************************************************************
 * @class   wosh::BusMTWorker
 * @brief   Worker process of the wosh::BusMT class based on wosh::ThreadMethod
 *          Independent Message dispatcher.
 *
 ****************************************************************************
 * @version $Id: BusMT.h 2868 2010-08-07 21:13:01Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_Core_BusMT_H__
 #define __WOSH_Core_BusMT_H__

 #include <woshDefs.h>
 #include <core/BusRing.h>
 #include <core/ThreadPool.h>


namespace wosh {

 #define _BusMT_NAME			"wosh.Bus.RingMT"

class BusMT;

class BusMTWorker : public ThreadMethod  {

	public:
		/**
		 * @brief  Empty constructor.
		 * @param [in] parent_ptr the parent coordinator pointer
		 */
		BusMTWorker( BusMT* parent_ptr );
		/**
		 * @brief  Empty destructor.
		 * @note   
		 */
		virtual ~BusMTWorker() { }

	public:
		void setMessage( Message* message_ptr );

		virtual void crashDetected( double probability );

	public:
		virtual void work();

	protected:
		BusMT* parent;					///< my parent coordinator

		Message* message;				///< the current message (to be delivered)

		mutable BusDebugInfo cDebug;	///< store temporary (real-time) debug info

};


class BusMT :	public wosh::Bus,
				protected wosh::ThreadImpl
 {
	WOSH_BUS(wosh::BusMT)

	public:
		/**
		 * @brief  Empty constructor.
		 * @param [in] busname the name to assign to the bus (usually it's something like 'wosh.Bus.Devices')
		 * @note   Raise the BusManager created (1) event.
		 */
		BusMT( const std::string& busname = "" );
		/**
		 * @brief  Empty destructor.
		 * @note   Raise the BusManager destroying (0) event.
		 */
		virtual ~BusMT();

	public:
		virtual void setParentObject( const Object* parent );
		WRESULT setWorkersCount( int count );
	//	virtual void crashDetected( double probability );


/** @name Bus interface - management
 * @{
 ******************************************************************************/
	public:
		virtual WRESULT startBus( unsigned long timeout = LIMIT_ULONG_MAX );
		virtual WRESULT stopBus( unsigned long timeout = LIMIT_ULONG_MAX );

		virtual bool isBusRunning() const	{ return Thread::isThreadRunning(); }

//@}
/** @name Internal methods
 * @{
 ******************************************************************************/
	protected:
		/**
		 * @brief  Message dispatcher iterates listeners and notifies the message.
		 * @param [in] message the message to be forwarded to handlers
		 * @param [in] cDebug reference to debug information holder, it will be updated on each round
		 * @note  Message won't be copied neither modified by this function, an
		 *        explicit copy may be done within listener's hanlder implementation.
		 */
		virtual void forward_message_to_listeners( const Message* message, BusDebugInfo& cDebug );
		/**
		 * @brief  Event dispatcher iterates listeners and notifies the event.
		 * @param [in] state the event to be forwarded to handlers
		 */
		virtual void forward_event_to_listeners( Bus::BUS_STATE state );

		/**
		 * @brief  Selects the first available idle workder and assignes the
		 *         delivery of next Message in the queue.
		 */
		virtual void runThread();



		virtual void processingStarted();

		virtual void processingFinished();

//@}
/** @name Internal vars
 * @{
 ******************************************************************************/
	protected:
		ThreadPool<BusMTWorker>* workersPool;	///< collection of worker processes

//@}
	protected:
		friend class wosh::BusMTWorker;		///< let my worker-processes access protected functions
		friend class wosh::BusManager;		///< let my 'manager' access protected functions


}; // class def


}; // namespace wosh

#endif //__WOSH_Core_BusMT_H__
